<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\admin;

use app\common\facade\extend\RedisExtend;
use app\common\facade\model\AdminLogModel;
use app\common\facade\model\AdminModel;
use app\common\facade\model\AdminRoleModel;
use app\common\facade\model\AdminRuleModel;
use think\facade\Request;
use think\helper\Str;

class Admin extends BaseAdmin
{

    /**
     * 登录
     */
    public function login($param = [])
    {

        $adminInfo = self::adminInfo($param);

        if (!$adminInfo || !password_verify($param['password'], $adminInfo['password'])) exception('帐号或者密码不正确');

        $multiApp    = multiApp('admin');
        $accessLogin = $multiApp . $adminInfo['id'] . millisecond() . Str::random();
        $accessLogin = hash('sha512', $accessLogin);

        RedisExtend::del($multiApp . $adminInfo['accessLogin']);

        $adminInfo['accessLogin'] = $accessLogin;
        $adminInfo['arEnable']    = $adminInfo['roleHasOne']['enable'];
        $adminInfo['ruleId']      = $adminInfo['roleHasOne']['ruleId'];

       return self::baseLogin($adminInfo, $multiApp, 2);

        return $adminInfo;
    }

    /**
     * 管理员详情
     */
    public function adminInfo($param = [])
    {

        if (isset($param['name']) && $param['name']) $where[] = ['name', '=', $param['name']];

        if (isset($param['enable']) && $param['enable']) $where[] = ['enable', '=', $param['enable']];

        if (isset($param['projectId']) && $param['projectId']) $where[] = ['projectId', '=', $param['projectId']];

        if (isset($param['accessLogin']) && $param['accessLogin']) $where[] = ['accessLogin', '=', $param['accessLogin']];

        if (isset($param['id']) && $param['id']) $where[] = ['id', '=', $param['id']];

        if (!isset($where)) exception();

        return AdminModel::adminInfo($where);
    }

    /**
     * 登录缓存
     */
    protected function baseLogin($param = [], $multiApp = '', $loginType = 0)
    {

        if ($param['enable'] != 2) exception('帐号已被禁用');

        if (!in_array($param['arEnable'], [0, 2])) exception('角色已被禁用');

        self::addSaveAdminLog($param);

        if ($loginType == 2):

            $ip = Request::ip();

            $saveUser = [
                'accessLogin' => $param['accessLogin'],
                'loginIp'     => $ip,
            ];

            $whereSaveUser[] = ['id', '=', $param['id']];

            AdminModel::editSave($saveUser, $whereSaveUser);

            if (isset($param['roleHasOne'])) unset($param['roleHasOne']);

            $loginInfo = [
                'id'       => $param['id'],
                'name'     => $param['name'],
                'loginIp'  => $param['loginIp'],
                'enable'   => $param['enable'],
                'roleId'   => $param['roleId'],
                'arEnable' => $param['arEnable'],
                'ruleId'   => $param['ruleId'],
            ];

            RedisExtend::hMSet($multiApp . $param['accessLogin'], $loginInfo, ['expire' => 7200]);
        endif;

        return $param;
    }

    /**
     * 添加操作日志
     */
    public function addSaveAdminLog($param = [])
    {

        $where = [
            ['path', '=', pathRule()]
        ];

        $infoRule = AdminRuleModel::info($where);

        if (!$infoRule) exception('路由不存在');

        if ($infoRule['enable'] != 2) exception('路由已被禁用');

        if ($param['roleId'] != 0):

            $ruleId = explodeMe($param['ruleId']);

            if (!in_array($infoRule['id'], $ruleId)) exception('没有权限访问!');
        endif;

        $paramLog = [
            'adminId'   => $param['id'],
            'roleId'    => $param['roleId'],
            'ruleId'    => $infoRule['id'],
            'ip'        => $param['loginIp'],
            'ruleId'    => $infoRule['id'],
        ];

        $addSave = AdminLogModel::addSave($paramLog);

        return $addSave;
    }

    /**
     * 检查登录
     */
    public function checkLogin($param = [])
    {

        $multiApp  = multiApp('admin');
        $loginInfo = RedisExtend::hGetAll($multiApp . $param['accessLogin']);

        if ($loginInfo):
            RedisExtend::expirePrefix($multiApp . $param['accessLogin'], 7200);
        else:
            if (!$loginInfo) exception('登录信息已过期，请重新登录', 90000);

            $loginInfo['arEnable'] = $loginInfo['roleHasOne']['enable'];
            $loginInfo['ruleId']   = $loginInfo['roleHasOne']['ruleId'];
        endif;

        $adminInfo = self::baseLogin($loginInfo);

        return $adminInfo;
    }

    /**
     * 管理员列表
     */
    public function adminList($param = [])
    {

        $loginInfo = $param['loginInfo'];

        $where = [];

        if (isset($param['name']) && $param['name']) $where[] = ['a.name', 'like', "%{$param['name']}%"];

        $adminList = AdminModel::adminList($where, $param['offsetLimit'], $param['lengthLimit']);

        return $adminList;
    }

    /**
     * 管理员【保存】
     */
    public function adminSave($param = [])
    {

        $where = [];

        $loginInfo = $param['loginInfo'];

        unset($param['loginInfo']);

        $whereInfo[] = ['name', '=', $param['name']];

        $info = AdminModel::info($whereInfo);

        if (isset($param['id']) && $param['id']):

            if ($param['id'] == 1) exception('该用户不支持修改');

            if ($info && $info['id'] != $param['id']) exception('名称已经存在');

            $where[] = ['id', '=', $param['id']];

            unset($param['id']);

            if (isset($param['password'])):
                if ($param['password']):
                    $param['password'] = password_hash($param['password'], PASSWORD_DEFAULT);
                else:
                    unset($param['password']);
                endif;
            endif;

            AdminModel::editSave($param, $where);
        else:

            if ($info) exception('名称已经存在');

            $password = isset($param['password']) && $param['password'] ? $param['password'] : '888888';

            $param['password'] = password_hash($password, PASSWORD_DEFAULT);

            AdminModel::addSave($param);
        endif;

        return true;
    }

    /**
     * 退出登录
     */
    public function loginOut($param = [])
    {

        $loginInfo = $param['loginInfo'];

        unset($param['loginInfo']);

        $multiApp = multiApp('admin');

        RedisExtend::del($multiApp . $param['accessLogin']);

        $where[] = ['id', '=', $loginInfo['id']];

        AdminModel::editSave(['accessLogin' => null], $where);

        return true;
    }

    /**
     * 权限【所有】
     */
    public function ruleAll($param = [])
    {

        $loginInfo = $param['loginInfo'];
        $where     = [];

        if (isset($param['enable']) && $param['enable']) $where[] = ['enable', '=', $param['enable']];

        $listsRule = AdminRuleModel::listsAll($where, '*', 'weigh DESC');

        return $listsRule;
    }

    /**
     * 角色【所有】
     */
    public function roleAll($param = [])
    {

        $loginInfo = $param['loginInfo'];

        $where = [];

        if (isset($param['enable']) && $param['enable']) $where[] = ['enable', '=', $param['enable']];

        return AdminRoleModel::listsAll($where);
    }

}
